<template>
  <div>
    <div>
      -------------
      {{ this.context }}
      ----------
    </div>

    <component
      :is="schema.xType"
      v-bind="schema"
      @propChange="
        (...args) => {
          set(schema, args[0], args[1]);
        }
      "
    ></component>
  </div>
</template>
<script>
import Vue from "vue";

export default {
  name: "QElement",
  props: {
    //特殊
    schema: {
      type: Object,
      required: true,
    },
  },
  //提供context上下文
  provide() {
    return this.getContext();
  },
  //获得祖先组件的context用于inheritContext
  inject: {
    context: {
      from: "context",
      default: () => {},
    },
  },
  methods: {
    //若不存在则需要添加可观察属性
    set(target, prop, val) {
      Vue.set(target, prop, val);
      // if (Object.keys(target).includes(prop)) {
      //   target[prop] = val;
      // } else {
      //   Vue.set(target, prop, val);
      // }
    },
    //实现类似amis的数据域级联的效果
    getContext() {
      if (this.schema.context !== undefined && this.schema.context !== null) {
        //是否实现从祖先组件继承context默认false覆盖
        if (this.schema.inheritContext ?? false) {
          if (this.context) {
            const inheritKeys = Object.keys(this.context);
            const currentKeys = Object.keys(this.schema.context);
            for (let inherit of inheritKeys) {
              if (!currentKeys.includes(inherit)) {
                this.set(this.schema.context, inherit, this.context[inherit]);
              }
            }
          }
        }
        return { context: this.schema.context };
      } else {
        //比如form是否允许创建自己的默认context呢、建议不允许
        return {};
      }
    },
  },
};
</script>
